#include "detk/file.h"
#include "deds/bool.h"
#include <string.h>
#include <assert.h>

/** This function corrects a path specifier by removing /./ directories
and moving /../ to the start of the path. */
void mx_path_fix(char *ptr)
{
	char *next;
	unsigned start = true;

	assert(ptr);

#ifdef __MSDOS__
	/** On MSDOS platforms leading drive specs are ignored. */
	if (ptr[1] == ':') {
		ptr += 2;
		if (*ptr == '/')
			++ptr;
	}
#endif

	/* Find slashes */
	next = strchr(ptr, '/');
	if (next)
		++next;

	/* Look for updirs */
	while ((ptr) && (next)) {

		/* Is the following dir an updir, and the previous one not */
		if ((next[0] == '.') && (next[1] == '.') && (ptr[0] != '.')
			&& (ptr[1] != '.'))
			strcpy(ptr, next + 3);

		/* Remove /./ combinations except at the start */
		else if ((ptr[0] == '.') && (ptr[1] == '/') && (ptr + 2 == next)
				 && (!start))
			strcpy(ptr, ptr + 2);

		/* Look at the next slashes */
		else
			ptr = next;

		next = strchr(ptr, '/');
		if (next)
			++next;

		start = false;
	}
}
